package interfaces;

import java.util.*;
import java.awt.*;

import javax.swing.JOptionPane;

import net.xoetrope.xui.*;
import net.xoetrope.xui.exception.*;
import net.xoetrope.xui.validation.*;
public class ExceptionHandler implements XExceptionHandler
{
	boolean pageValidation = false;
	private XPage currentPage;
	Vector errors, warnings;
	
	public ExceptionHandler( XPage page )
	{
		currentPage = page;
	}
	public boolean handleException( Object comp, Exception ex, Object xvalidator )
	{
		XValidator validator = ( XValidator ) xvalidator;
		if ( ( validator.getLevel() == validator.LEVEL_ERROR ) && ( ! pageValidation ) ){
			currentPage.showMessage( "Input error", ex.getMessage() );
			return true;
		}
		String msg = validator.getMessage();
		if ( validator.getLevel() == validator.LEVEL_ERROR )
			errors.add( msg );
		else
			warnings.add( msg );
		return true;
	}
	public int accumulateMessages( boolean start, int level )
	{
		pageValidation = start;
		if ( pageValidation ){
			errors = new Vector();
			warnings = new Vector();
		} else {
			if ( errors.size() > 0 || warnings.size() > 0 ) {
				Toolkit.getDefaultToolkit().beep();
//				currentPage.showMessage( "Error", formatMessages() );
				JOptionPane.showMessageDialog(null, formatMessages());
			}
		}
		return level;
	}
	private String formatMessages()
	{
		String msg = "";
		for ( int i = 0; i < errors.size(); i++ )
			msg += "error :" + errors.elementAt( i ) + "\n";
		for ( int i = 0; i < warnings.size(); i++ )
			msg += "warning :" + warnings.elementAt( i ) + "\n";
		return msg;
	}
	@Override
	public boolean handleEventHandlerException(XProject arg0, Object arg1,
			Throwable arg2) {
		return false;
	}
}